﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;

namespace auxiliary_proj
{
    public partial class FormComposeMessage : Form
    {
        String subject, message;
        DateTime msgDate;
        bool isViewed;
        private static MySqlCommand command;
        private static MySqlConnection connection;
        private static MySqlDataReader reader;
        public static int receive_emp;
        List<string> names_list = new List<string>();

        //default constructor
        public FormComposeMessage()
        {
            InitializeComponent();
            this.tsCbFontSize.TextChanged += new EventHandler(tsCbFontSize_TextChanged); //event handler
            this.tsCbFontFamily.TextChanged += new EventHandler(tsCbFontFamily_TextChanged); //event handler
            connection = new MySqlConnection(Program.getConnection()); //get Connection
            qGetUsers();
        }

        //parameterized constructor that specifies who the sender of the message is
        public FormComposeMessage(string sender)
        {
            InitializeComponent();
            MsgSubjectTextBox.Text = "RE: " + Singleton.getFormShowMessage().getSubject();
            this.tsCbFontSize.TextChanged += new EventHandler(tsCbFontSize_TextChanged);
            this.tsCbFontFamily.TextChanged += new EventHandler(tsCbFontFamily_TextChanged);
            connection = new MySqlConnection(Program.getConnection());
            qGetOneUser(sender);
        }

        public string Subject
        {
            get
            {
                return subject;
            }
            set
            {
                this.subject = value;
            }
        }
        public string Message
        {
            get
            {
                return message;
            }
            set
            {
                this.message = value;
            }
        }
        public DateTime MsgDate
        {
            get
            {
                return msgDate;
            }
            set
            {
                this.msgDate = value;
            }
        }
        public bool IsViewed
        {
            get
            {
                return isViewed;
            }
            set
            {
                this.isViewed = value;
            }
        }

        //Queries the database for the one user who sends the message
        public void qGetOneUser(string sender)
        {
            //before adding records in combobox clear previous data
            ToMsgComboBox.Items.Clear();
            string query = "SELECT CONCAT( first_name,  ' ', last_name ) AS users ,user_name FROM USER WHERE user_name ='" + sender + "' order by last_name";
            Cursor.Current = Cursors.WaitCursor;
            try
            {
                command = new MySqlCommand(query, connection);
                connection.Open();
                reader = command.ExecuteReader();
                {
                    while (reader.Read())
                    {
                        //adds the user to the combobox 
                        ToMsgComboBox.Items.Add(reader["users"].ToString());
                        ToMsgComboBox.SelectedIndex = 0;
                        names_list.Add(reader["user_name"].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            connection.Close();
            Cursor.Current = Cursors.Default;
        }

        //Gets all the users except the one who is logged in from the database and adds them to the combo box in the form 
        public void qGetUsers()
        {
            //before adding records in combobox clear previous data
            ToMsgComboBox.Items.Clear();
            string query = "SELECT CONCAT( first_name,  ' ', last_name ) AS users ,user_name FROM USER WHERE user_name !='" + Employee.User + "' order by last_name";
            try
            {
                command = new MySqlCommand(query, connection);
                connection.Open();
                reader = command.ExecuteReader();
                {
                    while (reader.Read())
                    {
                        ToMsgComboBox.Items.Add(reader["users"].ToString());
                        names_list.Add(reader["user_name"].ToString());
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            connection.Close();
        }

        //Inserts the message being sent from the user who is logged in to the user selected from the drop-down into the database
        public void iSendMsg(string send_emp)
        {
            if (MsgSubjectTextBox.Text.Length != 0)
            {
                if (rtbMessageBox.Text.Length != 0)
                {
                    string insertMessage = "INSERT INTO MESSAGING (receive_user_id, " +
                                "send_user_id, message_id, subject, message, timestamp, isViewed)" +
                                "VALUES ('" + send_emp + "', '" + Employee.User + "',NULL, '" + MsgSubjectTextBox.Text + "','" + (string)rtbMessageBox.Rtf.Replace(@"\", @"\\") +
                                "', CURRENT_TIMESTAMP, 0);";
                    if (Query.nonQuery(insertMessage))
                    {
                        MessageBox.Show("Message Sent!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                        MessageBox.Show("Failed To Send", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
                else MessageBox.Show("Message field empty!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("Subject field empty!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        //runs the send message query
        private void sendMsgBtn_Click(object sender, EventArgs e)
        {
            receive_emp = ToMsgComboBox.SelectedIndex;
            if (receive_emp == -1)
                MessageBox.Show("Please enter a recipient!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            else
                iSendMsg(names_list[receive_emp]);
        }

        int fontStyle = (int)FontStyle.Regular;
        bool boldSelected = false;
        float size = 11;
        string font = "Arial";

        private void tsBold_Click(object sender, EventArgs e)
        {
            if (boldSelected)
            {
                boldSelected = false;
                fontStyle -= (int)FontStyle.Bold;
            }
            else
            {
                boldSelected = true;
                fontStyle += (int)FontStyle.Bold;
            }

            rtbMessageBox.SelectionFont = new Font(font, size, (FontStyle)fontStyle);
        }

        bool italicsSelected = false;
        private void tsItalics_Click(object sender, EventArgs e)
        {
            if (italicsSelected)
            {
                italicsSelected = false;
                fontStyle -= (int)FontStyle.Italic;
            }
            else
            {
                italicsSelected = true;
                fontStyle += (int)FontStyle.Italic;
            }

            rtbMessageBox.SelectionFont = new Font(font, size, (FontStyle)fontStyle);
        }

        bool underlineSelected = false;
        private void tsUnderline_Click(object sender, EventArgs e)
        {
            if (underlineSelected)
            {
                underlineSelected = false;
                fontStyle -= (int)FontStyle.Underline;
            }
            else
            {
                underlineSelected = true;
                fontStyle += (int)FontStyle.Underline;
            }

            rtbMessageBox.SelectionFont = new Font(font, size, (FontStyle)fontStyle);
        }

        private void tsCbFontSize_TextChanged(object sender, EventArgs e)
        {
            string reg = @"\d+";
            Regex r = new Regex(reg);
            bool isValue = r.IsMatch(tsCbFontSize.Text);
            if (isValue)
            {
                size = float.Parse(tsCbFontSize.Text);
                rtbMessageBox.SelectionFont = new Font(font, size, rtbMessageBox.Font.Style);
            }
            else
                MessageBox.Show("Enter a numeric value!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void tsCbFontFamily_TextChanged(object sender, EventArgs e)
        {
            font = tsCbFontFamily.Text.Trim();
            rtbMessageBox.SelectionFont = new Font(font, size, rtbMessageBox.Font.Style);
        }

        private void tsColor_Click(object sender, EventArgs e)
        {
            ColorDialog colorPicker = new ColorDialog();
            if (colorPicker.ShowDialog() == DialogResult.OK)
            {
                tsColor.ForeColor = colorPicker.Color;
                rtbMessageBox.SelectionColor = colorPicker.Color;
            }
        }
    }
}